const Service = require('../../../core/service/ApiService');

class AgedDao extends Service {

    async findAgedById(aged_id, community_id_list) {
        const query = this.knex
            .select('aged_id', 'aged.name', 'aged_pic', 'svc_status')
            .select({town_name: 'town.name'}, {community_name: 'community.name'}, {subdistrict_name: 'subdistrict.name'})
            .from('aged')
            .join('town', 'aged.town_id', 'town.town_id')
            .join('community', 'aged.community_id', 'community.community_id')
            .join('subdistrict', 'aged.subdistrict_id', 'subdistrict.subdistrict_id')
            .where('aged.aged_id', '=', aged_id)
            .where('aged.status', '=', this.constant.AGED_STATUS.ENABLE)
            .where('aged.community_id', 'in', community_id_list)
            .limit(1);
        const result = await this.model.query(query.toString(), {type: this.model.QueryTypes.SELECT});
        return result.length !== 0 ? result[0] : null;
    }

    //根据名字（可选）搜索老人
    async searchAged(pn, ps, kw, community_id_list) {
        const query = this.knex
            .select('aged_id', 'aged.name', 'aged_pic', 'svc_status')
            .select({town_name: 'town.name'}, {community_name: 'community.name'}, {subdistrict_name: 'subdistrict.name'})
            .from('aged')
            .join('town', 'aged.town_id', 'town.town_id')
            .join('community', 'aged.community_id', 'community.community_id')
            .join('subdistrict', 'aged.subdistrict_id', 'subdistrict.subdistrict_id')
            .where('aged.status', '=', this.constant.AGED_STATUS.ENABLE)
            .where('aged.community_id', 'in', community_id_list)
            .offset((pn - 1) * ps)
            .limit(ps);
        if ('kw') {
            query.where('aged.name', 'like', `%${kw}%`);
        }
        query.orderBy('svc_status', 'ASC');
        return this.model.query(query.toString(), {type: this.model.QueryTypes.SELECT});
    }
}

module.exports = AgedDao;
